package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.Follow;
import com.hmdp.entity.ScrollResult;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IFollowService;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {
    @Resource
    private IUserService userService;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private IFollowService followService;

    @Override
    public Result queryBlogById(long id) {
        //根据id查询blog
        Blog blog = getById(id);
        //封装blog
        loadBlog(blog);
        return Result.ok(blog);
    }

    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(blog ->{
            loadBlog(blog);
        });
        return Result.ok(records);
    }

    @Override
    public Result orderLike(Long id) {
        //判断用户是否对该博客点过赞
        Long userId = UserHolder.getUser().getId();
        try {
            if(!BooleanUtil.isTrue(stringRedisTemplate.opsForValue().setIfAbsent("orderLike"+userId,""))){
                Thread.sleep(20);
                return orderLike(id);
            }
            Double score = stringRedisTemplate.opsForZSet().score("orederLike:z:" + id, userId.toString());
            //点过取消点赞
            if(score!=null){
                boolean isSuccess = update().setSql("liked=liked-1").eq("id", id).update();
                //删除redis记录
                if (isSuccess)
                stringRedisTemplate.opsForZSet().remove("orederLike:z:" + id,userId.toString());
            }else {//没点过
                boolean isSuccess = update().setSql("liked=liked+1").eq("id", id).update();
                //添加redis记录
                if (isSuccess)
                stringRedisTemplate.opsForZSet().add("orederLike:z:" + id,userId.toString(),System.currentTimeMillis());
            }
            stringRedisTemplate.delete("orderLike"+userId);
        } catch (InterruptedException e) {
            stringRedisTemplate.delete("orderLike"+userId);
            e.printStackTrace();
        }
        return Result.ok();
    }

    @Override
    public Result getTopLikes(long id) {
        List<UserDTO>likesCollect= Collections.emptyList();
        //获得该博客所点赞的前五个用户
        Set<String> top5 = stringRedisTemplate.opsForZSet().range("orederLike:z:"+id, 0, 4);
        if(top5!=null&& !top5.isEmpty()) {
                likesCollect = top5.stream().map((sid) -> {
                User byId = userService.getById(Long.valueOf(sid));
                UserDTO userDTO = new UserDTO();
                BeanUtil.copyProperties(byId, userDTO);
                return userDTO;
            }).collect(Collectors.toList());
        }
        return Result.ok(likesCollect);
    }

    @Override
    public Result saveBlog(Blog blog) {
        // 获取登录用户
        UserDTO user = UserHolder.getUser();
        blog.setUserId(user.getId());
        // 保存探店博文
        boolean isSuccess = save(blog);
        if (!isSuccess) return Result.fail("发布失败");
        //查询用户的所有粉丝
        List<Follow> follows = followService.query().eq("follow_user_id", user.getId()).list();
        //向每个粉丝的博客箱投递博客
        for (Follow follow : follows) {
            String key="blogBox:"+follow.getUserId();
            stringRedisTemplate.opsForZSet().add(key,blog.getId().toString(),System.currentTimeMillis());
        }
        return Result.ok(blog.getId());
    }

    @Override
    public Result getIdlesBlogs(long lastId, int offset) {
        UserDTO user = UserHolder.getUser();
        String key="blogBox:"+user.getId();
        Set<String> blogIds = stringRedisTemplate.opsForZSet().reverseRangeByScore(key,0,lastId, offset,5);
        if (blogIds==null||blogIds.isEmpty())return Result.ok(Collections.emptyList());
        AtomicLong nextId = new AtomicLong();
        List<Blog> blogs = blogIds.stream().map((id) -> {
            Long value = Long.valueOf(id);
            nextId.set(value);
            Blog blog = getById(value);
            loadBlog(blog);
            return blog;
        }).collect(Collectors.toList());
        Double score = stringRedisTemplate.opsForZSet().score(key,nextId.toString());
        int size = stringRedisTemplate.opsForZSet().rangeByScore(key
                        , score
                        , score)
                .size();
        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(score.longValue());
        scrollResult.setOffset(size);
        return Result.ok(scrollResult);
    }

    private void loadBlog(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
        //判断用户是否对该博客点赞过并对isLike字段赋值
        UserDTO localUser = UserHolder.getUser();
        if(localUser==null)return;
        Double score = stringRedisTemplate.opsForZSet().score("orederLike:z:" + blog.getId(), localUser.getId().toString());
        blog.setIsLike(score!=null);
    }
}
